package com.duan.laugh.event.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.duan.laugh.event.pojo.entity.AfterEvent;
import com.duan.laugh.event.pojo.entity.EventHandlerRule;
import com.duan.laugh.event.mapper.EventHandlerRuleMapper;
import com.duan.laugh.event.pojo.entity.EventNotice;
import com.duan.laugh.event.pojo.vo.EventHandlerRuleVO;
import com.duan.laugh.event.pojo.vo.EventModelVO;
import com.duan.laugh.event.service.IAfterEventService;
import com.duan.laugh.event.service.IEventHandlerRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duan.laugh.event.service.IEventNoticeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringJoiner;

/**
 * <p>
 * 事件处理规则 服务实现类
 * </p>
 *
 * @author liutf
 * @since 2019-11-12
 */
@Service
public class EventHandlerRuleServiceImpl extends ServiceImpl<EventHandlerRuleMapper, EventHandlerRule> implements IEventHandlerRuleService {

    @Autowired
    private EventHandlerRuleMapper eventHandlerRuleMapper;
    @Autowired
    private IAfterEventService afterEventService;
    @Autowired
    private IEventNoticeService eventNoticeService;

    /**
     * 0010206 批量新增事件处理规则
     *
     * @param eventModelVO 事件模型
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByEventModelVO(EventModelVO eventModelVO) {
        // 事件模型id
        Long eventModelId = eventModelVO.getId();
        // 事件处理规则List
        List<EventHandlerRuleVO> eventHandlerRuleVOS = eventModelVO.getEventHandlerRules();
        EventHandlerRuleVO eventHandlerRuleVO = null;
        EventHandlerRule eventHandlerRule = null;
        AfterEvent afterEvent = null;
        EventNotice eventNotice = null;
        // 遍历事件处理规则
        for (int i = 0, j = eventHandlerRuleVOS.size(); i < j; i++) {
            eventHandlerRuleVO = eventHandlerRuleVOS.get(i);
            // 事件处理规则数据
            eventHandlerRule = new EventHandlerRule();
            BeanUtils.copyProperties(eventHandlerRuleVO, eventHandlerRule);
            eventHandlerRule.setEventModelId(eventModelId);
            super.save(eventHandlerRule);
            Long eventHandlerRuleId = eventHandlerRule.getId();
            // 后续事件数据
            List<AfterEvent> afterEvents = eventHandlerRuleVO.getAfterEvents();
            if (CollUtil.isNotEmpty(afterEvents)) {
                for (int i1 = 0, n1 = afterEvents.size(); i1 < n1; i1++) {
                    afterEvent = afterEvents.get(i1);
                    afterEvent.setEventHandlerRuleId(eventHandlerRuleId);
                }
                afterEventService.saveBatch(afterEvents);
            }
            // 事件通知数据
            List<EventNotice> eventNotices = eventHandlerRuleVO.getEventNotices();
            if (CollUtil.isNotEmpty(eventNotices)) {
                for (int i1 = 0, n1 = eventNotices.size(); i1 < n1; i1++) {
                    eventNotice = eventNotices.get(i1);
                    eventNotice.setEventHandlerRuleId(eventHandlerRuleId)
                            .setCreateTime(LocalDateTime.now());
                }
                eventNoticeService.saveBatch(eventNotices);
            }
        }
        return true;
    }

    /**
     * 0010207 根据ids修改事件处理规则
     *
     * @param eventModelVO 事件模型
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEventModelVO(List<EventHandlerRuleVO> eventHandlerRuleVOS) {
        EventHandlerRuleVO eventHandlerRuleVO = null;
        EventHandlerRule eventHandlerRule = null;
        AfterEvent afterEvent = null;
        EventNotice eventNotice = null;
        // 遍历事件处理规则
        for (int i = 0, j = eventHandlerRuleVOS.size(); i < j; i++) {
            eventHandlerRuleVO = eventHandlerRuleVOS.get(i);
            // 修改事件处理规则数据
            eventHandlerRuleVO.setEventModelId(null);
            super.saveOrUpdate(eventHandlerRuleVO);
            // 修改后续事件数据
            List<AfterEvent> afterEvents = eventHandlerRuleVO.getAfterEvents();
            if (CollUtil.isNotEmpty(afterEvents)) {
                afterEventService.saveOrUpdateBatch(afterEvents);
            }
            // 修改事件通知数据
            List<EventNotice> eventNotices = eventHandlerRuleVO.getEventNotices();
            if (CollUtil.isNotEmpty(eventNotices)) {
                eventNoticeService.saveOrUpdateBatch(eventNotices);
            }
        }
        return true;
    }

    /**
     * 0010208 根据事件模型ids批量删除事件处理规则
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByEventModelIds(String ids) {
        // 0010210 根据事件模型ids查询事件处理规则
        List<EventHandlerRule> eventHandlerRules = this.selectByEventModelIds(ids);
        // 组装 str ids
        StringJoiner stringJoiner = new StringJoiner(",");
        for (int i = 0, n = eventHandlerRules.size(); i < n; i++) {
            Long eventHandlerRuleId = eventHandlerRules.get(i).getId();
            stringJoiner.add(String.valueOf(eventHandlerRuleId));
        }
        // 0010209 根据ids批量删除事件处理规则
        return this.deleteByIds(stringJoiner.toString());
    }

    /**
     * 0010209 根据ids批量删除事件处理规则
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByIds(String ids) {
        List<String> strList = StrUtil.split(ids, ',', -1);
        super.removeByIds(strList);
        // 包括后续事件（0010307）
        afterEventService.deleteByEventHandlerRuleIds(ids);
        // 事件通知（0010407）
        return eventNoticeService.deleteByEventHandlerRuleIds(ids);
    }

    /**
     * 0010210 根据事件模型ids查询事件处理规则
     *
     * @param ids
     */
    @Override
    public List<EventHandlerRule> selectByEventModelIds(String ids) {
        List<String> strList = StrUtil.split(ids, ',', -1);
        return super.list(new LambdaQueryWrapper<EventHandlerRule>().in(EventHandlerRule::getEventModelId, strList));
    }

    /**
     * 0010211 根据事件模型id查询详细事件处理规则
     *
     * @param id
     * @return
     */
    @Override
    public List<EventHandlerRuleVO> selectEventHandlerRuleVOSByModelId(Long id) {
        List<EventHandlerRule> eventHandlerRules = super.list(new LambdaQueryWrapper<EventHandlerRule>().eq(EventHandlerRule::getEventModelId, id));
        EventHandlerRule eventHandlerRule = null;
        EventHandlerRuleVO eventHandlerRuleVO = null;
        List<EventHandlerRuleVO> eventHandlerRuleVOS = new ArrayList<>();
        for (int i = 0, n = eventHandlerRules.size(); i < n; i++) {
            eventHandlerRule = eventHandlerRules.get(i);
            Long eventHandlerRuleId = eventHandlerRule.getId();

            eventHandlerRuleVO = new EventHandlerRuleVO();
            BeanUtils.copyProperties(eventHandlerRule, eventHandlerRuleVO);

            List<AfterEvent> afterEventList = afterEventService.list(new LambdaQueryWrapper<AfterEvent>().eq(AfterEvent::getEventHandlerRuleId, eventHandlerRuleId));
            eventHandlerRuleVO.setAfterEvents(afterEventList);

            List<EventNotice> eventNoticeList = eventNoticeService.list(new LambdaQueryWrapper<EventNotice>().eq(EventNotice::getEventHandlerRuleId, eventHandlerRuleId));
            eventHandlerRuleVO.setEventNotices(eventNoticeList);

            eventHandlerRuleVOS.add(eventHandlerRuleVO);
        }
        return eventHandlerRuleVOS;
    }
}
